package jrain.fw.dao.common.handler;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

import jrain.fw.core.dao.ColumnFormatHandler;
import jrain.fw.core.dao.handler.IResultSetHandler;
import jrain.fw.core.utils.FwUtils;
import jrain.utils.date.DateUtils;
import jrain.utils.lang.StringUtils;

public class RowMapHandler implements IResultSetHandler<Map<String, Object>> {

	public Map<String, Object> handle(ResultSet rs, Map<String, Object> mapper) throws SQLException {
		ResultSetMetaData rsmd = rs.getMetaData();
		int cols = rsmd.getColumnCount();
		// 获取系统列信息
		if (rs.next()) {
			return handle1(rsmd, cols, rs, mapper);
		}
		return null;
	}

	
	
	public static Map<String, Object> handle1(ResultSetMetaData rsmd,int cols, ResultSet rs, Map<String, Object> mapper) throws SQLException {
		Map<String, Object> rowMap = new HashMap<String, Object>();
		for (int i = 1; i <= cols; i++) {
			String columnName = rsmd.getColumnLabel(i);
			String fieldCode = StringUtils.columnToField(columnName);
			int columnType = rsmd.getColumnType(i);
			Object value = rs.getObject(i);
			String format = StringUtils.trimNull(mapper.get(columnName));
			boolean b = false;
			if (!StringUtils.isEmpty(format)) {
				ColumnFormatHandler handler = FwUtils.getColumnFormatProvider().getHandler(format);
				if (handler != null) {
					handler.handler(rsmd, rs, i, columnType, columnName, fieldCode, value, rowMap);
					b = true;
				}
			}
			if (!b && Types.TIMESTAMP == columnType && value != null) {
				value = DateUtils.formatTime(value);
			}
			if(!b){
				rowMap.put(fieldCode, value);
			}
		}
		return rowMap;
	}

}